package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.BackTimeDAO;
import mwa.cs.dao.DefaultAddressDAO;
import mwa.cs.dao.ReceivePositionDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.SitesDAO;
import mwa.cs.database.Database;
import mwa.cs.model.BackTime;
import mwa.cs.model.DefaultAddress;
import mwa.cs.model.ReceivePosition;
import mwa.cs.util.JDate;

public class CS11012Srvl extends HttpServlet implements Servlet {
	
	private Database db;
	private int vnSiteId;
	private int vnUserId;
	private String vaAgentBrowser;
	private String vaUrlAddress;

    public CS11012Srvl() {
        super();
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	String vaProcessType = request.getParameter("process_type");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	vaUrlAddress = request.getParameter("url_address");
    	vaAgentBrowser = request.getParameter("agent_browser");
		if(vaProcessType.equals("getDefaultAddress")){
			getDefaultAddress(request,response);
		}
		else if (vaProcessType.equals("db")) {
			getDbStatus(request, response);
		}
		else if(vaProcessType.equals("manageData"))
		{
			// insert / edit
			manageData(request,response);
		}
		else
		{
			// delete
			delete(request,response);
		}
    }
    
    public void delete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
    {
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");	
		this.db = new Database();
		
		DefaultAddressDAO voDefaultAddressDAO = new DefaultAddressDAO(db);
		boolean vbResult = false;
		try {
			db.beginTransaction();
			vbResult = voDefaultAddressDAO.delete(vnSiteId);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS11012", JDate.getDate(), JDate.getTime(),vnUserId, "CS11012Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}
		
		db.close();
		
		if(vbResult)
			response.getWriter().write("success");
		else
			response.getWriter().write("fail");
    }
    
    public void manageData(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		this.db = new Database();
		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();

		String vaCity = request.getParameter("city");
		String vaDistrict = request.getParameter("district");
		String vaProvince = request.getParameter("province");
		String vaPostcode = request.getParameter("postcode");
		
		DefaultAddress voDefaultAddress = new DefaultAddress(vnSiteId, vaCity, vaDistrict, vaProvince, vaPostcode,
				vnUserId, vaDate, vaTime, vnUserId, vaDate, vaTime);
				
		DefaultAddressDAO voDefaultAddressDAO = new DefaultAddressDAO(db);
		
		boolean vbHasDefaultAddress = voDefaultAddressDAO.hasDefaultAddress(vnSiteId);
		boolean vbResult = false;
		
		if(vbHasDefaultAddress)
			// Update
			vbResult = voDefaultAddressDAO.update(voDefaultAddress);
		else
			// Add
			try {
				db.beginTransaction();
				vbResult = voDefaultAddressDAO.insert(voDefaultAddress);
				db.commit();
			} catch (Exception e) {
				SMErrorLogDAO.getInstance().addLog(0, "CS11012", JDate.getDate(), JDate.getTime(),vnUserId, "CS11012Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
				db.rollback();
				e.getMessage();
			}
		
		db.close();
		
		if(vbResult)
			response.getWriter().write("success");
		else
			response.getWriter().write("fail");
		
    }

    public void getDefaultAddress(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    	
    	request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8"); 
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColumn = null;
		PrintWriter voOut = response.getWriter();
		
		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			voObject.put("status", "connect_db_fail");
			voOut.print(voObject.toJSONString());
			return;
		}
		
		DefaultAddressDAO voDefaultAddressDAO = new DefaultAddressDAO(db);
		DefaultAddress voDefaultAddress = voDefaultAddressDAO.getDefaultAddress(vnSiteId);
		
		db.close();

		if(voDefaultAddress != null)
		{	
			voObject.put("status", "true");
			voObject.put("vnSiteId", voDefaultAddress.getVnSiteId());
			
			voObject.put("vaCityCode", voDefaultAddress.getVaCityCode());
			voObject.put("vaDistrictCode", voDefaultAddress.getVaDistrictCode());
			voObject.put("vaProvinceCode", voDefaultAddress.getVaProvinceCode());
			voObject.put("vaPostCode", voDefaultAddress.getVaPostCode());
			
			voObject.put("vnInsertUserId", voDefaultAddress.getVnInsertUserId());
			voObject.put("vaInsertDate", voDefaultAddress.getVaInsertDate());
			voObject.put("vaInsertTime", voDefaultAddress.getVaInsertTime());
			voObject.put("vnUpdateUserId", voDefaultAddress.getVnUpdateUserId());
			voObject.put("vaUpdateDate", voDefaultAddress.getVaUpdateDate());
			voObject.put("vaUpdateTime", voDefaultAddress.getVaUpdateTime());
		}
		else
		{
			voObject.put("status", "false");
		}
		
		voOut.print(voObject.toJSONString());
    }
    
	public void getDbStatus(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");

		PrintWriter voOut = response.getWriter();

		try {
			this.db = new Database();
			voOut.print("success");
		} catch (Exception ex) {
			voOut.print("connect_db_fail");
		} finally{
			db.close();
		}
	}
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}
}
